/*
 +----------------------------------------------------------------------
 + Title        : 购物车 pinia 存储
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2023-07-08
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 购物车 pinia 存储
 +----------------------------------------------------------------------
*/

import { reqAddCartAPI, reqCartListAPI, reqDeleteCartAPI, reqEditCartAPI } from "@/apis/cart";
import { defineStore } from "pinia";
import { ref, computed } from "vue";

export const useCartStore = defineStore('cart', () => {
    
    // 定义购物车商品列表
    const cartList:any = ref([])

    // 清空购物车
    const clearCart = () => {
        cartList.value = []
    }

    /**
     * 添加
     * @param good 
     * @returns 
     */
    const addCart = async (good:any) => {
        const result = await reqAddCartAPI({goods_id: good.goods_id, goods_sku_id: good.goods_sku_id, num: good.num})
        const sameIndex = cartList.value.findIndex((item:any) => item.goods_sku_id === good.goods_sku_id)
        // 逻辑：有相同的给goods累加数量，删除相同skuId的商品
        if (sameIndex > -1) {
            good.num = cartList.value[sameIndex].num + good.num
            cartList.value.splice(sameIndex, 1)
        }
        cartList.value.unshift(good)
        
        return result.message
    }

    /**
     * 删除
     * @param id 
     * @returns 
     */
    const deleteCart = async (id:any) => {
        const result = await reqDeleteCartAPI({ids: id})
        const index = cartList.value.findIndex((item:any) => item.id == id)
        cartList.value.splice(index, 1)
        return result.data
    }
		
    /**
     * 修改
     * @param data 
     * @returns 
     */
    const editCart = async (data:any) => {
        const result:any = await reqEditCartAPI(data)
        let ids = data.ids.split(',')
        ids.forEach((id:any) => {
            const updateGoods = cartList.value.find((item:any) => item.id == id)
            for (const key in data) {
                if (key != 'ids') {
                    updateGoods[key] = data[key]
                }
            }
        })
        
        return result.data
    }

    /**
     * 编辑商品SKU
     * @param data 
     * @returns 
     */
    const editCartSku = async (data:any) => {
        await reqEditCartAPI({
            ids: data.id, 
            goods_sku_id: data.newSku.skuId, 
            goods_name: data.goods_name, 
            goods_cover_url: data.goods_cover_url,
            num: data.num,
        })

        // 1. 获取旧的商品信息
        const oldGoods = cartList.value.find((item:any) => item.goods_sku_id === data.newSku.skuId)
        const { skuId, price, inventory_num, specsText } = data.newSku

        // 判断当前购物车里是否存在该商品SKU
        if (oldGoods != undefined) {
            // 2. 删除旧的商品
            const index = cartList.value.findIndex((item:any) => item.id == data.id)
            cartList.value.splice(index, 1)

            // 3. 合并一条新的商品信息
            let newGoods = { ...oldGoods, num: data.num, goods_sku_id: skuId, inventory_num, new_price: price, goods_sepc_option_text: specsText}
            newGoods.goods.price = price

            // 删除
            const sameIndex = cartList.value.findIndex((item:any) => item.goods_sku_id === newGoods.goods_sku_id)
            // 逻辑：有相同的给goods累加数量，删除相同skuId的商品
            if (sameIndex > -1) {
                newGoods.num = cartList.value[sameIndex].num + newGoods.num
                cartList.value.splice(sameIndex, 1)
            }
            cartList.value.unshift(newGoods)
        } else {
            const updateGoods = cartList.value.find((item:any) => item.id == data.id)
            updateGoods.goods_sku_id = skuId
            updateGoods.new_price = price
            updateGoods.inventory_num = inventory_num
            updateGoods.num = data.num
            updateGoods.goods_sepc_option_text = specsText
            updateGoods.goods.price = price
        }

        return 'ok'
    }
		
    /**
     * 列表
     * @returns 
     */
    const getCartList = async () => {
        const result:any = await reqCartListAPI()
        cartList.value = result.data.user_carts != null ? result.data.user_carts : []
        return 'ok'
    }

    /**
     * 有效商品的全选&反选
     * @param checked 
     * @returns 
     */
    const checkAllCart = async (checked:boolean) => {
        let ids = ''
        validList.value.forEach((item:any) => {
            ids += item.id + ','
        });
    
        ids = ids.substring(0,ids.length-1)

        await reqEditCartAPI({ids, is_checked: checked == true ? 1 : 0})
        const data:any = {is_checked: checked == true ? 1 : 0}

        ids.split(',').forEach(id => {
            const updateGoods = cartList.value.find((item:any) => item.id == id)
            for (const key in data) {
                if (key != 'ids') {
                    updateGoods[key] = data[key]
                }
            }
        })

        return 'ok'
    }

    // ------------------------- 计算属性 -------------------------

    // 有效商品列表
    const validList:any = computed(() => {
        return cartList.value.filter((item:any) => item.inventory_num > 0 && item.is_effective)
    })

    // 有效商品件数
    const validTotal = computed(() => {
        return validList.value.reduce((p:any, c:any) => p + c.num, 0)
    })
    
    // 有效商品总金额
    const validAmount = computed(() => {
        return validList.value.reduce((p:any, c:any) => {
            if (c.goods) {
                return p + c.new_price * c.num
            }
        }, 0)
    })

    // 无效商品列表
    const invalidList = computed(() => {
        return cartList.value.filter((item:any) => item.inventory_num == 0 || !item.is_effective)
    })

    // 已选商品列表
    const checkedList:any = computed(() => {
        return validList.value.filter((item:any) => item.is_checked)
    })

    // 已选商品总数
    const checkedTotal = computed(() => {
        return checkedList.value.reduce((p:any, c:any) => p + c.num, 0)
    })

    // 已选商品总金额
    const checkedAmount = computed(() => {
        return checkedList.value.reduce((p:any, c:any) => {
            if (c.goods) {
                return p + c.new_price * c.num
            }
        }, 0)
    })

    // 是否全选
    const isCheckAll = computed(() => {
        return checkedList.value.length == validList.value.length && validList.value.length != 0
    })
		
    return {
        cartList,
        addCart,
        deleteCart,
        editCart,
        getCartList,
        checkAllCart,
        editCartSku,
        clearCart,

        validList,
        validTotal,
        validAmount,
        invalidList,
        checkedList,
        checkedTotal,
        checkedAmount,
        isCheckAll,
    }
},

// 持久化
{
    persist: {
        storage: {
            getItem(key) {
                return uni.getStorageSync(key)
            },
            setItem(key, value) {
                uni.setStorageSync(key, value)
            },
        }
    }
}
)